#include "stdafx.h"
#include "VSCtxMenuFixHook.h"

static const WCHAR g_szRegSubKey[] = L"SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7";
static const WCHAR g_szRegValueNameVS10[] = L"10.0";
static const WCHAR g_szRegValueNameVS11[] = L"11.0";
static const WCHAR g_szVsFileName[] = L"Common7\\IDE\\devenv.exe";

static LPWSTR GetVisualStudio10FileName();
static LPWSTR GetVisualStudio11FileName();
static LPWSTR GetVisualStudioFileName(LPCWSTR lpRegSubKey, LPCWSTR lpRegValueName, LPCWSTR lpVsFileName);
static LPWSTR GetVisualStudioInstallDir(LPCWSTR lpRegSubKey, LPCWSTR lpRegValueName);

BOOL GetIsVisualStudioProcess()
{
    CMyBuffer<WCHAR> currentProcessFileName(GetCurrentProcessFileName());

    if (currentProcessFileName.IsNull())
    {
        return FALSE;
    }

    CMyBuffer<WCHAR> visualStudio10FileName(GetVisualStudio10FileName());

    if (!visualStudio10FileName.IsNull())
    {
        if (lstrcmpi(currentProcessFileName.GetBuffer(), visualStudio10FileName.GetBuffer()) == 0)
        {
            return TRUE;
        }
    }

    CMyBuffer<WCHAR> visualStudio11FileName(GetVisualStudio11FileName());

    if (!visualStudio11FileName.IsNull())
    {
        if (lstrcmpi(currentProcessFileName.GetBuffer(), visualStudio11FileName.GetBuffer()) == 0)
        {
            return TRUE;
        }
    }

    return FALSE;
}

static LPWSTR GetVisualStudio10FileName()
{
    return GetVisualStudioFileName(g_szRegSubKey, g_szRegValueNameVS10, g_szVsFileName);
}

static LPWSTR GetVisualStudio11FileName()
{
    return GetVisualStudioFileName(g_szRegSubKey, g_szRegValueNameVS11, g_szVsFileName);
}

static LPWSTR GetVisualStudioFileName(LPCWSTR lpRegSubKey, LPCWSTR lpRegValueName, LPCWSTR lpVsFileName)
{
    CMyBuffer<WCHAR> vsIntallDir(GetVisualStudioInstallDir(lpRegSubKey, lpRegValueName));

    if (vsIntallDir.IsNull())
    {
        return NULL;
    }

    CMyBuffer<WCHAR> result(lstrlen(vsIntallDir.GetBuffer()) + lstrlen(lpVsFileName) + 1);

    lstrcpy(result.GetBuffer(), vsIntallDir.GetBuffer());
    lstrcat(result.GetBuffer(), lpVsFileName);

    return result.Detach();
}

static LPWSTR GetVisualStudioInstallDir(LPCWSTR lpRegSubKey, LPCWSTR lpRegValueName)
{
    CMyBuffer<WCHAR> result(MAX_PATH + 1);

    if (result.IsNull())
    {
        return NULL;
    }

    DWORD cbData;

    cbData = sizeof(WCHAR) * (MAX_PATH + 1);
    if (RegGetValue(HKEY_CURRENT_USER, lpRegSubKey, lpRegValueName, RRF_RT_REG_SZ, NULL, (LPBYTE)result.GetBuffer(), &cbData) == ERROR_SUCCESS)
    {
        return result.Detach();
    }

    cbData = sizeof(WCHAR) * (MAX_PATH + 1);
    if (RegGetValue(HKEY_LOCAL_MACHINE, lpRegSubKey, lpRegValueName, RRF_RT_REG_SZ, NULL, (LPBYTE)result.GetBuffer(), &cbData) == ERROR_SUCCESS)
    {
        return result.Detach();
    }

    return NULL;
}
